package cn.fu.validato.rule;

import java.text.SimpleDateFormat;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 
 * @ClassName: InspectorValidator
 * @Description: 自定义校验处理类
 * @author zhangxiaofu
 * @date 2016年5月28日 下午10:45:23
 *
 */
public class InspectorValidator implements ConstraintValidator<Inspector, Object> {

	private String length;// 固定长度
	private String max;// 数字：最大
	private String min;// 数字：最小
	private String maxLength;// 最长
	private String minLength;// 最短
	private String reg;// 字符串：正则
	private String enumeration;// 枚举
	private Boolean isDate;

	// 重写校验方法
	public boolean isValid(Object value, ConstraintValidatorContext arg1) {

		try {
			if (!"0".equals(length) && !new Integer((value + "").length()).equals(new Integer(length)))
				return false;

			if (!"0".equals(max) && (Integer.parseInt(max) < Integer.parseInt(value + "")))
				return false;

			if (!"0".equals(min) && (Integer.parseInt(min) > Integer.parseInt(value + "")))
				return false;

			if (!"0".equals(maxLength) && new Integer(maxLength) < (value + "").length())
				return false;

			if (!"0".equals(minLength) && new Integer(minLength) > (value + "").length())
				return false;

			if (!"".equals(reg) && !Pattern.compile(reg).matcher(value.toString()).matches())
				return false;

			if (!"".equals(enumeration) && (enumeration).indexOf(value + "") < 0)
				return false;

			if (isDate) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				try {
					format.setLenient(false);
					format.parse(value + "");
				} catch (Exception e) {
					return false;
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	// 重写初始化
	public void initialize(Inspector paramA) {
		this.length = paramA.length() + "";
		this.max = paramA.max() + "";
		this.min = paramA.min() + "";
		this.maxLength = paramA.maxLength() + "";
		this.minLength = paramA.minLength() + "";
		this.reg = paramA.reg() + "";
		this.enumeration = paramA.enumeration() + "";
		this.isDate = new Boolean(paramA.enumeration());
	}

}